<template>
	<view class="container">
		<scroll-view @scrolltolower="getMoreChatUserVo">
			<view v-for="(chatUserVo,index) in chatUserVoList" :key="index" @click="trunToChat(chatUserVo)">
				<view style="height: 10px;"></view>
				<view class="chatUserVoItem">
					<view style="display: flex;align-items: center;">
						<uni-badge class="uni-badge-left-margin" :text="chatUserVo.unReadChatNum" absolute="rightTop"
							size="small">
							<u--image :showLoading="true" :src="urlConstruct(chatUserVo.userAvatar)" width="50px"
								height="50px" :fade="true" duration="450">
								<view slot="error" style="font-size: 24rpx;">加载失败</view>
							</u--image>
						</uni-badge>
					</view>
					<view style="margin: 10rpx;"></view>
					<view
						style="line-height: 20px;width: 100%;display: flex;justify-content: space-between;flex-direction: column;">
						<view style="display: flex;	justify-content: space-between;">
							<view>
								<view class="nickname">{{chatUserVo.userNickname}}
								</view>
								<view class="content">{{chatUserVo.lastChatContent}}</view>
							</view>
							<view class="date">{{formatDateToString(chatUserVo.lastChatDate)}}</view>
						</view>

						<!-- <view style="height: 10px;"></view> -->
						<u-line></u-line>
					</view>
				</view>

			</view>
		</scroll-view>
		<view v-if="!chatUserVoList || chatUserVoList.length==0">
			<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png" texColor="#ffffff" iconSize="160"
				iconColor="#D7DEEB" text="当前聊天列表为空" textColor="#D7DEEB" textSize="18" marginTop="30">
			</u-empty>
		</view>
		
	</view>
</template>

<script>
	import {
		listChatUserVo
	} from "@/api/market/chat.js";
	import {
		listChat
	} from "@/api/market/chat.js";
	import Vue from 'vue';
	import {
		picUrlConstruct
	} from "@/utils/picUrlConstruct.js";


	export default {
		data() {
			return {
				chatUserVoList: [],
				page: {
					pageNum: 1,
					pageSize: 15
				},

			}
		},
		created() {
			
		},
		methods: {
			urlConstruct(url) {
				return picUrlConstruct(url);
			},
			/**
			 * 滑动到底部，自动加载新一页的数据
			 */
			getMoreChatUserVo() {
				this.page.pageNum++;
				this.listChatUserVo();
			},
			listChatUserVo() {
				listChatUserVo(this.page).then(res => {
					// console.log("res:"+JSON.stringify(res.rows))
					// this.chatUserVoList = res.rows;
					for (var i = 0; i < res.rows.length; i++) {
						this.chatUserVoList.push(res.rows[i]);
					}
				})
			},
			/**
			 * 格式化日期
			 * @param {Object} date
			 */
			formatDateToString(dateStr) {
				let date = new Date(dateStr);
				// 今天的日期
				let curDate = new Date();
				if (date.getFullYear() == curDate.getFullYear() && date.getMonth() == curDate.getMonth() && date
					.getDate() == curDate.getDate()) {
					// 如果和今天的年月日都一样，那就只显示时间
					return this.toDoubleNum(date.getHours()) + ":" + this.toDoubleNum(date.getMinutes());
				} else {
					// 如果年份一样，就只显示月日
					return (curDate.getFullYear() == date.getFullYear() ? "" : (date.getFullYear() + "-")) + this
						.toDoubleNum((
							date
							.getMonth() + 1)) +
						"-" +
						this.toDoubleNum(date.getDate());
				}
			},
			/**
			 * 如果传入的数字是两位数，直接返回；
			 * 否则前面拼接一个0

			 * @param {Object} num
			 */
			toDoubleNum(num) {
				if (num >= 10) {
					return num;
				} else {
					return "0" + num;
				}
			},
			/**
			 * 转到私聊页面
			 */
			trunToChat(chatUserVo) {
				let you = {
					avatar: chatUserVo.userAvatar,
					nickname: chatUserVo.userNickname,
					username: chatUserVo.userName
				}
				uni.navigateTo({
					url: "/pages/chat/chat?you=" + encodeURIComponent(JSON.stringify(you))
				})
			},
			/**
			 * 获取socket
			 */
			getSocket() {
				return this.Constant.softType === 0 ? this.$socket : this.$store.state.ws;
			},
			/**
			 * 检测socket是否正常
			 */
			checkSocket() {
				return new Promise((resolve, reject) => {
					let socket = this.getSocket();
					if (!socket) {
						// 连接已经断开，重新建立连接
						this.$webSocketService.initWebsocket(this.$store, this.Constant).then(() => {
							resolve();
						})
					} else {
						resolve();
					}
				})
			},
			/**
			 * 接收消息
			 */
			receiveMessage() {
				this.checkSocket().then(() => {
					if (this.Constant.softType == 0) {
						this.$socket.onMessage((response) => {
							// console.log("接收消息：" + response.data);
							let message = JSON.parse(response.data);

							// 收到消息，将未读消息数量加一
							for (var i = 0; i < this.chatUserVoList.length; i++) {
								if (this.chatUserVoList[i].userName == message.from) {
									this.chatUserVoList[i].unReadChatNum++;
									// 显示对方发送的最新消息
									listChat(message.from, {
										pageNum: 1,
										pageSize: 1
									}).then(res => {
										this.chatUserVoList[i].lastChatContent = res.rows[0]
											.content
									});
									break;
								}
							}
						})
					} else if (this.Constant.softType == 1) {
						// 网站类型
						let socket = this.$store.state.ws;
						let _that = this;
						// 网站类型
						socket.onmessage = function(response) {
							console.log("接收消息：" + response.data);
							let message = JSON.parse(response.data);

							// 收到消息，将未读消息数量加一
							for (var i = 0; i < _that.chatUserVoList.length; i++) {
								if (_that.chatUserVoList[i].userName == message.from) {
									_that.chatUserVoList[i].unReadChatNum++;
									// 显示对方发送的最新消息
									listChat(message.from, {
										pageNum: 1,
										pageSize: 1
									}).then(res => {
										_that.chatUserVoList[i].lastChatContent = res.rows[0].content
									});
									break;
								}
							}
						};
					}
				})
			},

		},
		onLoad(e) {
			this.checkSocket();
			this.receiveMessage();
		},
		onShow: function() {
			this.chatUserVoList = [];
			this.listChatUserVo();
		},
	}
</script>

<style lang="scss">
	.container {
		padding: 20rpx;

		.chatUserVoItem {
			display: flex;
			margin: 0 5px;

			.nickname {
				font-weight: 700;
			}

			.content {
				color: #A7A7A7;
				font-size: 14px;

				/* 让消息只显示1行，超出的文字内容使用...来代替 */
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 1;
				-webkit-box-orient: vertical;
			}

			.date {
				color: #A7A7A7;
				font-size: 12px;
			}
		}

		// .uni-badge-left-margin {
		// 	margin-left: 10px;
		// }
	}
</style>